import AddCircleIcon from '@mui/icons-material/AddCircle';
import { Backdrop, Box, CircularProgress, Typography } from '@mui/material';
import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';

import Member from '../../api/member/member';
import MemberManager from '../../api/member/member-manager';
import MainLayout from '../../components/HOCs/main-layout';
import MembersTable from '../../components/members/members-table';
import { GFSButton } from '../../components/shared/button/gfs-button';
import { createDialog } from '../../components/shared/dialogs/dynamic-dialogs';
import { DialogTypes } from '../../components/shared/dialogs/dynamic-dialogs/types-mapping';
import { modifyScholarDialog } from '../../components/shared/dialogs/scholar-management/modify-scholar';
import { useInfiniteScroll } from '../../hooks/infinitive-scroll';
import { useLoadScholar } from '../../hooks/scholar-load-more';

export default function MembersPage() {
    const [pageLoading, setPageLoading] = useState(false);
    const [currentItems, setCurrentItems] = useState([]);

    const { loading, items, hasNextPage, error, loadMore } = useLoadScholar();

    const [sentryRef] = useInfiniteScroll({
        loading,
        hasNextPage,
        onLoadMore: loadMore,
        disabled: !!error,
        rootMargin: '0px 0px 400px 0px'
    });
    const [loadingAction, setLoadingAction] = useState(false);

    useEffect(() => {
        const load = async () => {
            setPageLoading(true);
            await loadMore();
            setPageLoading(false);
        };
        load().then();
    }, []);

    useEffect(() => {
        setCurrentItems(items ? items : []);
    }, [items]);

    const openCreateDialog = () => {
        createDialog(DialogTypes.MODIFY_SCHOLAR, () =>
            modifyScholarDialog({
                open: true,
                data: {
                    type: 'create'
                },
                onSubmit: handleAfterAddScholar
            })
        );
    };

    const handleAfterAddScholar = (item) => {
        const newItems = Member.fromJSON(item);
        const items = [newItems, ...currentItems];
        setCurrentItems(items);
        window.scrollTo(0, 0);
    };

    const handleAfterEditScholar = (item) => {
        const editedItem = Member.fromJSON(item);
        const items = [...currentItems];
        const currentIndex = items.findIndex((cur) => cur.id === editedItem.id);
        if (currentIndex !== -1) {
            items[currentIndex] = { ...editedItem };
        }
        setCurrentItems(items);
    };

    const onEdit = (item) => {
        createDialog(DialogTypes.MODIFY_SCHOLAR, () =>
            modifyScholarDialog({
                open: true,
                data: {
                    type: 'update',
                    item: { ...item }
                },
                onSubmit: handleAfterEditScholar
            })
        );
    };

    const onDelete = async (currentItem) => {
        setLoadingAction(true);
        try {
            const { deleted } = await MemberManager.delete(currentItem.id);
            if (deleted) {
                const newItems = [...currentItems].filter((item) => item.id !== currentItem.id);
                setCurrentItems(newItems);
                toast.success(`Delete member successfully!`, {
                    theme: 'dark'
                });
            } else {
                console.log('Cant delete item ' + currentItem);
            }
        } catch (e) {
            toast.error(e.message || `Cant delete item ${currentItem.name}`, { theme: 'dark' });
        } finally {
            setTimeout(() => setLoadingAction(false));
        }
    };

    return (
        <MainLayout>
            <Box sx={{ p: 6 }}>
                <Box className="d-flex justify-content-between">
                    <Typography variant="h2" color="white" sx={{ pb: 3 }}>
                        Member Management
                    </Typography>
                    <GFSButton onClick={openCreateDialog}>
                        New Member <AddCircleIcon sx={{ ml: 1 }} />
                    </GFSButton>
                </Box>
                <MembersTable
                    pageLoading={pageLoading}
                    items={currentItems}
                    error={error}
                    loading={loading}
                    hasNextPage={hasNextPage}
                    editItem={onEdit}
                    deleteItem={onDelete}
                    sentryRef={sentryRef}
                />
            </Box>
            <Backdrop
                sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
                open={loadingAction}
            >
                <CircularProgress color="inherit" />
            </Backdrop>
        </MainLayout>
    );
}
